﻿using System;
using HttpApiGateway.Config;
using HttpApiGateway.Interface;
using HttpService.Interface;

namespace HttpApiGateway.PlugIn
{
        internal class CorsPlugIn : IHttpPlugIn
        {
                private readonly ICrossDomainConfig _Config;

                public bool IsEnable => _Config.IsEnable;

                public string Name => "CorsPlugIn";

                public CorsPlugIn()
                {
                        this._Config = new CrossDomainConfig();
                }

                public void Init()
                {

                }
                public void Exec(IRoute route, IHttpHandler handler)
                {
                        Uri uri = handler.Request.UrlReferrer;
                        if (uri == null || uri.Authority != handler.Request.Url.Authority)
                        {
                                return;
                        }
                        else if (this._Config.CheckUrlReferrer(uri))
                        {
                                string header = handler.Request.Headers["Access-Control-Request-Headers"];
                                if (string.IsNullOrEmpty(header))
                                {
                                        header = this._Config.AllowHead;
                                }
                                handler.Response.SetHead("Access-Control-Allow-Credentials", "true");
                                handler.Response.SetHead("Access-Control-Allow-Headers", header);
                                handler.Response.SetHead("Access-Control-Allow-Origin", string.Format("{1}://{0}", uri.Authority, uri.Scheme));
                                handler.Response.SetHead("Access-Control-Max-Age", this._Config.MaxAge);
                                handler.Response.SetHead("Access-Control-Request-Method", this._Config.Method);
                                if (handler.Request.HttpMethod == "OPTIONS")
                                {
                                        handler.Response.SetHttpStatus(System.Net.HttpStatusCode.NoContent);
                                        handler.Response.End();
                                }
                        }
                        else if (!this._Config.AllowCredentials)
                        {
                                handler.Response.SetHttpStatus(System.Net.HttpStatusCode.NonAuthoritativeInformation);
                                handler.Response.End();
                        }
                }

                public void Dispose()
                {
                   
                }
        }
}
